package cn.wolfcode.wolf2w.business.service.impl;

import cn.wolfcode.wolf2w.business.api.RemoteNoteService;
import cn.wolfcode.wolf2w.business.api.domain.Note;
import cn.wolfcode.wolf2w.business.api.domain.StrategyEs;
import cn.wolfcode.wolf2w.business.query.SearchQuery;
import cn.wolfcode.wolf2w.business.repository.StrategyEsRepository;
import cn.wolfcode.wolf2w.business.service.ISearchService;
import cn.wolfcode.wolf2w.business.service.IStrategyEsService;
import cn.wolfcode.wolf2w.common.core.constant.SecurityConstants;
import cn.wolfcode.wolf2w.common.core.domain.R;
import cn.wolfcode.wolf2w.common.core.web.page.TableDataInfo;
import cn.wolfcode.wolf2w.destination.RemoteDestinationService;
import cn.wolfcode.wolf2w.destination.entity.TaDestination;
import cn.wolfcode.wolf2w.member.api.RemoteUserInfoService;
import cn.wolfcode.wolf2w.member.api.domain.UserInfo;
import cn.wolfcode.wolf2w.strategy.RemoteStrategyService;
import cn.wolfcode.wolf2w.strategy.entity.Strategy;

import com.baomidou.mybatisplus.extension.service.IService;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
public class SearchServiceImpl implements ISearchService {

    @Autowired
    private ElasticsearchRestTemplate template;
    @Autowired
    private RemoteStrategyService remoteStrategyService;

    @Autowired
    private RemoteNoteService remoteNoteService;

    @Autowired
    private RemoteUserInfoService remoteUserInfoService;

    @Autowired
    private RemoteDestinationService remoteDestinationService;

    @Override
    public <T> Page<T> searchHighLight(Class<T> mysqlClazz, Class<?> clazz, SearchQuery qo, String... fields) {
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        builder.withQuery(
                QueryBuilders.multiMatchQuery(qo.getKeyword(), fields)
        );
        PageRequest pageRequest = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize());
        builder.withPageable(pageRequest);
        HighlightBuilder.Field[] fs = new HighlightBuilder.Field[fields.length];
        for (int i = 0; i < fs.length; i++) {
            fs[i] = new HighlightBuilder.Field(fields[i])
                    .preTags("<span style='color:red;'>")
                    .postTags("</span>");
        }
        builder.withHighlightFields(fs);

        SearchHits<?> searchHits = template.search(builder.build(), clazz);
        long total = searchHits.getTotalHits();
        List<T> list = new ArrayList<>();
        for (SearchHit<?> searchHit : searchHits) {
            String id = searchHit.getId();
            System.err.println("_id: "+id);
            T t = null;
            if(mysqlClazz == Strategy.class){
                t = (T) remoteStrategyService.getOne(Long.valueOf(id), SecurityConstants.INNER).getData();
            }else if (mysqlClazz == Note.class){
                t=(T) remoteNoteService.getOne(Long.valueOf(id), SecurityConstants.INNER).getData();
            }else if (mysqlClazz == UserInfo.class){
                t= (T) remoteUserInfoService.getOne(Long.valueOf(id), SecurityConstants.INNER).getData();
            }else if (mysqlClazz == TaDestination.class){
                t= (T) remoteDestinationService.getById(Long.valueOf(id)).getData();
            }
            Map<String, List<String>> highlightFields = searchHit.getHighlightFields();
            Set<String> keySet = highlightFields.keySet();
            for (String key : keySet) {
                List<String> stringList = highlightFields.get(key);
                StringBuffer sb = new StringBuffer();
                for (String s : stringList) {
                    sb.append(s);
                }
                String value = sb.toString();
                System.err.println("高亮的列："+key+"     高亮的值："+value);
                try {
                    BeanUtils.setProperty(t, key, value);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
            list.add(t);
        }

        return new PageImpl<T>(list, pageRequest, total);
    }
}
